# -*- coding: utf-8 -*-
import os
from datetime import datetime
from flask import render_template, current_app, redirect, url_for, request, \
    flash
from flask_login import login_required, current_user
import time
from scrapy_jsonrpc.jsonrpc import JsonRpcError
from ..task import generate_index, INDEX_LOCK_FILE

from . import main
from .. import db
from ..models import User, Job, Role, UserStatus, Source
from .forms import EditForm, ChangePassword
from ..decorators import admin_required
from ..utility import SpiderManager


@main.before_app_request
@admin_required
def before_request():
    pass

@main.route('/')
@login_required
def index():
    today = time.strftime('%Y-%m-%d', time.localtime(time.time()))

    jobs = Job.query.group_by('open_date_int').all()
    user_count = User.query.filter_by(status=1).count()
    today_user = User.query.filter(User.create_date > today).count()
    job_count = Job.query.count()
    today_job = Job.query.filter(Job.create_date > today).count()
    # a =
    # for job in jobs:
    #     print "%s"%(job)
    return render_template('index.html',
                           user_count=user_count,
                           job_count=job_count,
                           today_user=today_user,
                           today_job=today_job)


@main.route('/users/')
# @main.route('/users/page/<int:page>')
@login_required
def user_list():
    page = request.args.get('page', 1, type=int)
    pagination = User.query.paginate(
        page, per_page=current_app.config['USERS_PER_PAGE'],
        error_out=False)
    # pagination = Pagination(user, page, 2)

    return render_template('main/users.html',
                           pagination=pagination,
                           users=pagination.items)


@main.route('/user/profile/<int:id>', methods=['post', 'get'])
@login_required
def user_profile(id):
    user = User.query.get_or_404(id)
    form = EditForm(id)
    pform = ChangePassword()
    which_form = request.form.get('form')

    _follows = user.followed.order_by('star.create_date DESC').all()
    follows = [{"job": item.followed, "time": item.create_date} for item in _follows]

    form.role.choices = [(r.id, r.name) for r in Role.query.order_by('id')]
    form.status.choices = UserStatus.getAll()

    if which_form == '1' and form.validate_on_submit():
        user.username = form.username.data
        user.nickname = form.nickname.data
        user.role_id = form.role.data
        user.status = form.status.data
        db.session.add(user)
        db.session.commit()
        flash(u'修改成功。')
    elif pform.validate_on_submit():
        user.password = pform.new_password.data
        db.session.add(user)
        db.session.commit()
        flash(u'修改密码成功。')
    form.username.data = user.username
    form.nickname.data = user.nickname
    form.role.data = user.role_id
    form.status.data = user.status

    return render_template('main/profile.html',
                           user=user,
                           form=form,
                           pform=pform,
                           which_form=which_form,
                           follows=follows)


@main.route('/user/delete/<int:id>')
@login_required
def delete_user(id):
    if id == 1:
        flash(u'此用户不能删除。')
    else:
        user = User.query.get_or_404(id)
        db.session.delete(user)
        db.session.commit()
        flash(u'用户删除成功。')
    return redirect(url_for('main.user_list'))


@main.route('/jobs/')
def job_list():
    page = request.args.get('page', 1, type=int)
    keyword = request.args.get('keyword', '', type=unicode)
    # job = Job.query.filter()
    # pagination = Pagination(job, page, 2)
    job_query = Job.query

    if keyword:
        # qstr = u'%%%s%%' % keyword
        # or_(Job.title.like(qstr), Job.content.like(qstr))
        job_query = job_query.whoosh_search(keyword)
    pagination = job_query.paginate(
        page, per_page=current_app.config['JOBS_PER_PAGE'],
        error_out=False)

    return render_template('main/jobs.html',
                           pagination=pagination,
                           jobs=pagination.items)


@main.route('/job/view/<int:id>')
def job_detail(id):
    job = Job.query.get_or_404(id)

    return render_template('main/job_detail.html', job=job)


@main.route('/job/delete/<int:id>')
def status_job(id):
    job = Job.query.get_or_404(id)
    job.status = not job.status
    db.session.add(job)
    db.session.execute('update star set status=%d where job_id=%d'%(job.status, id))
    db.session.commit()
    return redirect(url_for('main.job_list'))


@main.route('/spider/')
def spider_manager():
    command = request.args.get('command', '', str)
    which = request.args.get('s', '', str)
    id = request.args.get('id', '', str)

    spiders = []
    manager = SpiderManager()
    try:
        available_spider = manager.available_spider()['spiders']
        spiders_status = manager.spiders_status()
        tmp_spiders = {}

        if command:
            if command == 'index_all':
                if os.path.exists(INDEX_LOCK_FILE):
                    flash(u'任务进行中...')
                else:
                    generate_index.apply_async()

            elif command == 'run' and which:
                res = manager.open(which)
                if res.status_code and res.json()['status'] == 'ok':
                    flash(u'命令已发送，请刷新查看状态。')
                else:
                    flash(u'服务器错误。')
            elif command == 'stop' and id:
                res = manager.stop(id)
                if res.status_code and res.json()['status'] == 'ok':
                    flash(u'命令已发送，请刷新查看状态。')
                else:
                    flash(u'服务器错误。')
            elif command == 'run_all':
                for s in available_spider:
                    manager.open(s)
            else:
                flash(u'操作不存在。')

            return redirect(url_for('main.spider_manager'))

        for s in spiders_status['pending']:
            tmp_spiders[s['spider']] = {
                "name": s['spider'],
                "id": s['id'],
                'status': 'pending',
            }

        for s in spiders_status['finished']:
            tmp_spiders[s['spider']] = {
                "name": s['spider'],
                "id": s['id'],
                'status': 'finished',
            }

        for s in spiders_status['running']:
            tmp_spiders[s['spider']] = {
                "name": s['spider'],
                "id": s['id'],
                'status': 'running',
            }
            print tmp_spiders[s['spider']]

        for spider in available_spider:
            if spider in tmp_spiders:
                tmp_spiders[spider].update({
                    'source': Source.query.get(spider),
                })
                spiders.append(tmp_spiders[spider])
            else:
                spiders.append({
                    "name": spider,
                    "source": Source.query.get(spider),
                    "status": 'pending',
                })
    except Exception, e:
        print e

    return render_template('main/spider.html', spiders=spiders)
